package com.df.bpm.utils.businessViewer;

import com.df.bpm.dto.BusinessInputDTO;
import com.df.bpm.entity.BusinessEntity;
import com.df.bpm.entity.BusinessInformation;
import com.df.bpm.entity.BusinessInputs;
import com.df.bpm.utils.businessViewer.inputsDialogServices.BusinessInputDTOservice;
import com.df.bpm.utils.businessViewer.inputsDialogServices.BusinessInputsService;
import com.df.bpm.utils.businessViewer.stepsTableServices.EntityService;
import com.df.common.utils.CommonUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class InputsDialog {

    int unit;
    JDialog jd=new JDialog();
    JPanel jp=new JPanel();

    List<JTextField> fields;
    Font iFont;
    Integer selectResultID;
    BusinessInputsService businessInputsService;
    BusinessInputDTOservice businessInputDTOservice;

    EntityService entityService;

    BusinessInformation businessInformation;

    boolean isVisible=false;

    boolean isInit=true;

    public InputsDialog() {
        unit= (int) MainPanel.unit;
        iFont=new Font("宋体", Font.PLAIN, (int) (MainPanel.unit));
        jd.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                // 关闭窗口时触发
            }
        });
        jd.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        jd.setSize(20*unit, 20*unit);
        businessInputsService=new BusinessInputsService();
        businessInputDTOservice=new BusinessInputDTOservice();
        entityService=new EntityService();
    }

    public void changeVisible(){
        isVisible=!isVisible;
    }

    public void show(BusinessInformation businessInformation) {
        this.businessInformation=businessInformation;
        repaint4ThisDialog();
    }

    private void repaint4ThisDialog() {
        jd.remove(jp);
        if(isInit) {
            jd.setLocationRelativeTo(null);
        }
        jd.setLayout(null);
        jp=new JPanel();
        jp.setLayout(null);
        jp.setSize(jd.getSize());

        fields=new ArrayList<>();
        addFields4SelectDialog(fields,"名称");
        addFields4SelectDialog(fields,"类型");

        JTextField lastField=fields.get(fields.size()-1);
        JScrollPane scr=new JScrollPane();
        scr.setLocation(unit,lastField.getY()+lastField.getHeight()+unit);
        scr.setSize(jp.getWidth()-3*unit, jp.getHeight()-4*unit-scr.getY());
        jp.add(scr);


        for(JTextField field:fields){
            field.addKeyListener(
                    new KeyAdapter(){
                        public void keyPressed(KeyEvent e)
                        {
                            if(e.getKeyChar()==KeyEvent.VK_ENTER )   //按回车键执行相应操作;
                            {
                                search4ThisDialog(fields,scr);
                            }
                        }
                    });
        }

        jd.add(jp);
        jd.setModal(false);
        jd.setAlwaysOnTop(true);
        jd.repaint();
        jd.setTitle(businessInformation.getBusinessDesc()+" 的输入体清单");
        if(CommonUtils.varIsNotBlank(Main.mainPanel) ){
            if(isInit) {
                jd.setLocation((int) (Main.mainPanel.maxSize.getWidth() - jd.getWidth() - unit), unit);
                isInit = false;
            }
            jd.setVisible(isVisible);
        }

        search4ThisDialog(fields,scr);

    }

    private void search4ThisDialog(List<JTextField> fields, JScrollPane scr) {
        BusinessInputDTO temp=new BusinessInputDTO().setBusinessInformationIndex(businessInformation.getBusinessInformationIndex());
        if (CommonUtils.varIsNotBlank(fields.get(0).getText())) {
            temp.setEntityName(fields.get(0).getText());
        }
        if (CommonUtils.varIsNotBlank(fields.get(1).getText())) {
            temp.setTypeName(fields.get(1).getText());
        }
        List<BusinessInputDTO> list = businessInputDTOservice.getList4Like(temp);
        showBusinessInputDTOlist4SelectDialog(scr,list);
    }

    private void showBusinessInputDTOlist4SelectDialog(JScrollPane scr, List<BusinessInputDTO> list) {
        scr.getViewport().removeAll();
        String[] title = {"ID","序号", "名称", "类型"};
        DefaultTableModel model = new DefaultTableModel(null, title){
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;//不允许编辑，留作触发双击或拖拽
            }
        };
        if(CommonUtils.varIsNotBlank(list)) {
            for (int n=0;n<list.size();n++) {
                BusinessInputDTO row=list.get(n);
                model.addRow(new Object[]{row.getBusinessEntityIndex(),list.size()-n, row.getEntityName(), row.getTypeName()});
            }
        }
        model.addRow(new Object[]{null, null, null, null});
        list.add(new BusinessInputDTO().setBusinessInformationIndex(businessInformation.getBusinessInformationIndex()));
        JTable iTable=EntityTypeDialog.newTable4SelectDialog(model, iFont);
        iTable.getColumnModel().getColumn(3).setPreferredWidth(10);
        Main.hideCol(iTable,0);
        scr.getViewport().add(iTable);
        iTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = iTable.rowAtPoint(e.getPoint());
                int col = iTable.columnAtPoint(e.getPoint());
                if (row >= 0 ) {
                    if (e.getClickCount() == 2) {// 处理双击事件
                        String inputID=""+iTable.getValueAt(row, 0);
                        if(col==1 && CommonUtils.varIsNotBlank(inputID)){//不为空的双击代表选中
                            selectResultID=list.get(row).getBusinessEntityIndex();
                            jd.dispose();//选好窗口消失
                        }else{// 双击空行触发新增 BusinessEntity
                            Integer result=null;
                            if((col==2)||(col==3)){
                                result=updateInput(row,list);
                            }
                            if(result!=null && result>0){
                                search4ThisDialog(fields,scr);
                            }
                        }

                    }
                }
            }
        });

    }

    private Integer updateInput(int row, List<BusinessInputDTO> list) {
        Integer result=null;
        Integer oldValue=list.get(row).getBusinessInputsIndex();
        BusinessEntity oldEntity=null;
        if(CommonUtils.varIsNotBlank(oldValue)){
            oldEntity=entityService.getEntity(oldValue);
        }
        Integer newValue=new EntityDialog(entityService).selectEntity(oldEntity);
        if(newValue!=null && !Objects.equals(oldValue, newValue)){
            Integer inputID=list.get(row).getBusinessInputsIndex();
            if(CommonUtils.varIsBlank(inputID)){
                inputID=null;
            }
            BusinessInputs temp=new BusinessInputs()
                    .setBusinessEntityIndex(newValue)
                    .setBusinessInputsIndex(inputID)
                    .setBusinessInformationIndex(businessInformation.getBusinessInformationIndex());
            result=updateBusinessInputs(temp);
        }
        return result;
    }

    private Integer updateBusinessInputs(BusinessInputs temp) {
        if(temp.getBusinessInputsIndex()!=null && temp.getBusinessEntityIndex()==-1){
            return businessInputsService.delete(temp.getBusinessInputsIndex());
        }
        return businessInputsService.updateInput(temp);
    }



    private void addFields4SelectDialog(List<JTextField> fields, String colName) {
        EntityTypeDialog.addFields4SelectDialog(fields, colName, unit, iFont, jp);
    }

}
